import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pt_manage/generated/l10n.dart';
import 'package:pt_manage/util/toast_util.dart';

import '../component/text_icon_button.dart';
import 'home_page.dart';

class IndexPage extends StatefulWidget {
  const IndexPage({super.key});

  @override
  State<IndexPage> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  int _selectedIndex = 0;
  int _last = 0;

  @override
  Widget build(BuildContext context) {
    final bodyList = [const HomePage()];

    return PopScope(
        canPop: false,
        onPopInvoked: (didPop) {
          if (didPop) return;
          int now = DateTime.now().millisecondsSinceEpoch;
          if (now - _last > 2000) {
            _last = now;
            ToastUtil.show(S.of(context).backExitMsg);
            return;
          }
          SystemNavigator.pop();
        },
        child: Material(
            child: Scaffold(
          body: SafeArea(
            child: bodyList[_selectedIndex],
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {},
            tooltip: "添加",
            shape: const CircleBorder(),
            child: const Icon(Icons.add),
          ),
          floatingActionButtonLocation:
              FloatingActionButtonLocation.centerDocked,
          bottomNavigationBar: BottomAppBar(
            shape: const CircularNotchedRectangle(),
            notchMargin: 10,
            height: 60,
            padding: const EdgeInsets.all(0),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildTextIconButton(context, "首页", Icons.home, 0, () {}),
                _buildTextIconButton(context, "动态", Icons.send, 1, () {}),
                const SizedBox(),
                _buildTextIconButton(
                    context, "消息", Icons.message_outlined, 3, () {}),
                _buildTextIconButton(context, "我的", Icons.person, 4, () {}),
              ],
            ),
          ),
        )));
  }

  Widget _buildTextIconButton(BuildContext context, String text, IconData icon,
      int selectIndex, Function onTap) {
    Color color = Theme.of(context).colorScheme.primary;
    bool isSelected = _selectedIndex == selectIndex;
    return TextIconButton(
      onTap: () {
        setState(() => _selectedIndex = selectIndex);
        onTap();
      },
      text: Text(
        text,
        style: TextStyle(fontSize: 10, color: isSelected ? color : null),
      ),
      icon: Icon(
        icon,
        color: isSelected ? color : null,
      ),
      type: TextIconButtonType.imageTop,
      margin: 0,
    );
  }
}
